<template>
  <div class="siteTable" id="siteTable">
    <div class="siteTable_header">
      <!-- 功能按钮 -->
      <div class="siteTable_header_right">
        <div>
          <span class="siteStatus_label">站点状态：</span>
          <a-select
            v-model:value="status"
            style="width: 120px"
            :options="siteStatus"
            :style="{ width: '96px' }"
            @select="onSearchSite"
          >
          </a-select>
        </div>
        <div class="searchContent">
          <a-input
            v-model:value="searchSiteName"
            placeholder="搜索站点名称"
            style="width: 192px"
          >
            <template #suffix>
              <i class="iconfont icon-search" @click="onSearchSite"></i>
            </template>
          </a-input>
        </div>
      </div>
    </div>
    <draggtreetable
      :columns="siteColumns"
      :dataSource="configData.records"
      :rowSelection="0"
      :rowKey="rowKey"
      @dragEnd="dragEnd"
      :scroll="scroll_siteTable"
      :defaultExpandAllRows="true"
      ele="siteTable"
    >
      <template #bodyCell="{ column, text, record }" v-if="configData.records.length">
        <template v-if="column.dataIndex === 'siteName'">
          <div class="siteName">
            <div>{{ record.siteName }}</div>
          </div>
        </template>
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'status'">
          <a-switch
            @click="switchChange(record, '')"
            size="small"
            v-model:checked="record.status"
            v-if="!record.status"
          />
          <a-popconfirm
            placement="topRight"
            ok-text="确认"
            cancel-text="取消"
            @confirm="switchChange(record, 'isClose')"
            v-else
          >
            <template #title>
              <p style="width: 197px">
                {{ closeSiteTips }}
              </p>
            </template>
            <a-switch
              size="small"
              v-model:checked="record.status"
              :disabled="!record.openClosePerm"
              @change="record.status = true"
            />
          </a-popconfirm>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a
            class="operation"
            :class="!record.editPerm ? 'disable' : ''"
            @click="editSite(record)"
            >{{ oparation[0] }}</a
          >
          <a class="operation" @click="scanSite(record)">{{ oparation[1] }}</a>
        </template>
      </template>
    </draggtreetable>
    <base-modal
      :width="modAlProps.width"
      :isVisible="isVisible"
      :title="modAlProps.title"
      :buttons="buttons"
      :isCancleBtn="isCancleBtn"
      @handleOk="buttonMessage"
      @handleCancle="isVisible = false"
      class="site_modal"
      v-if="isVisible"
    >
      <template v-slot:body>
        <!-- 创建子站点form表单展示部分 -->
        <creat-child-site
          :parentTitle="parentTitle"
          :parentId="parentId"
          ref="SITEFORM"
          v-if="isVisible && isVisibleForm"
        ></creat-child-site>
        <!-- 回收站表格展示部分 -->
        <div class="baseTable">
          <baseTable
            :columns="siteRecycleColumns"
            :dataSource="configData_recycle.records"
            :isSelect="true"
            :scroll="scroll"
            ref="siteRecycleBaseTables"
            :isShowPagination="isShowPagination"
            :showCheckDelete="showCheckDelete"
            :total="configData_recycle.total"
            @changePage="changePage"
            v-if="!isVisibleForm"
          >
            <template #otherOpration>
              <a-button @click="restore2Data" :disabled="!rowSelection.length"
                >还原</a-button
              >
              <a-popconfirm
              :disabled="!rowSelection.length"
                placement="topRight"
                ok-text="确认"
                cancel-text="取消"
                @confirm="deleteSelectedAll"
              >
                <template #title>
                  <p style="width: 197px">永久删除站点后不可恢复,是否继续删除？</p>
                </template>
                <a-button type="primary" danger :disabled="!rowSelection.length"
                  >永久删除</a-button
                >
              </a-popconfirm>
            </template>
          </baseTable>
        </div>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, createVNode, computed, nextTick } from "vue";
import { useRouter } from "vue-router";
import draggtreetable from "@/components/table/draggTreeTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import baseTable from "@/components/table/baseTable.vue";
import columnsName from "@/components/table/tableConfig/columnsName";
import request from "@/api/index";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import { Modal, message } from "ant-design-vue";
import type { SelectProps } from "ant-design-vue";
import baseModal from "@/components/modal/baseModal.vue";
import creatChildSite from "./creatSiteForm/creatChildSite.vue";
import { scrollType, modeProp } from "@/type.d";
import { getTableScroll } from "@/components/table/tableConfig/table";
import { routerPerm } from "@/utils/common";
//interface
interface DataList {
  [propName: string | number]: any;
}
//data
const btnPerm = ref<any[]>([]);
const router = useRouter();
//表格数据
const siteColumns = ref(columnsName.siteColumns); //站点表头
const oparation = ref<string[]>(["编辑", "浏览"]); //站点表格操作项
const rowKey = ref<String | Number>("id"); // 选中的表格项
const status = ref<String>("全部"); // 筛选过滤表格数据
const siteStatus = ref<SelectProps["options"]>([
  {
    value: "",
    label: "全部",
  },
  {
    value: "0",
    label: "关闭",
  },
  {
    value: "1",
    label: "开启",
  },
]); // 站点开启、关闭状态
const searchSiteName = ref<String>(""); // 按站点名搜索站点

const isVisible = ref<Boolean>(false); // 模态框是否可见
const isVisibleForm = ref<Boolean>(false); // 模态框中的form是否可见

const closeSiteTips = ref<String>(
  "关闭站点后，前台用户将无法浏览站点内容，站点管理后台依旧可以操作"
); //关闭站点提示语
const deleteTips = ref<String>(""); //站点删除提示语
// 创建新站点模态框相关数据
const SITEFORM = ref<any>(null); //获取子组件
const modAlProps: modeProp = reactive({
  width: "M",
  title: "新建站点",
});
//模态框button按钮个数和文案修改
let buttons = ref<DataList[]>([]);
let isCancleBtn = ref<Boolean>(false);
const parentTitle = ref<string | number>("");
const parentId = ref<string | number>("");
// 模态框中basetable相关数据
const siteRecycleColumns = ref(columnsName.siteRecycleColumns); //站点回收站列表表头;
let configData = reactive<DataList>({ records: [] }); // 站点表格数据
const configData_recycle = reactive<DataList>({ total: 0, size: 10, records: [] }); // 回收站站点表格数据
let scroll: scrollType = reactive({ y: 400, isFixed: false }); // 表单滚动设置
let scroll_siteTable: scrollType = reactive({ y: "100", isFixed: false }); // 表单滚动设置
const siteRecycleBaseTables = ref<any>(null); // basetable的ref
let rowSelection = ref<(string | number)[]>([]); // 表格中已选中的表单项
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(10);
// watch
buttons = computed(() => {
  let arr: DataList[] = [];
  if (isVisibleForm.value) {
    arr = [
      {
        text: "保存",
        "html-type": "submit",
      },
      {
        text: "保存并继续新建",
        "html-type": "submit",
      },
    ];
  } else {
    arr = [];
  }
  return arr;
});
// computed
rowSelection = computed(() => {
  return siteRecycleBaseTables.value ? siteRecycleBaseTables.value.selectedRowKeys : [];
});
// methods
const getRdecord = async (datas: DataList = {}) => {
  // 获取表格数据
  const data: {} = {
    siteName: searchSiteName.value || "",
    status: status.value == "全部" ? "" : status.value,
  };
  const telData = await request.fetchSiteManageTabledData(data);
  configData.records = [];
  if (telData) {
    configData.records.push(telData);
  }
  let dataList: DataList[] = JSON.parse(JSON.stringify(configData.records));
  configData.records = JSON.parse(JSON.stringify(loop(dataList, {})));
  nextTick(() => {
    let obj = getTableScroll(74, "siteTable");
    scroll_siteTable.y = obj.y;
  });
};
// 获取站点回收站数据
const getRecycleRdecord = async (datas: DataList = {}) => {
  const data: {} = {
    pageNumber: datas.pageNumber || pageCurrent.value,
    pageSize: datas.pageSize || pageSize.value,
    siteName: "",
  };
  const telData = await request.fetchSiteManageRecycleTable(data);
  configData_recycle.records = [];
  if (telData) {
    configData_recycle.total = telData.total;
    configData_recycle.records = telData.records;
  }
};
// 还原已选回收站数据到站点列表
const restore2Data = async () => {
  let keys: (string | number)[] = rowSelection.value;
  await request
    .fetchsiteManageTabledDataRestore({ ids: keys })
    .then((res: DataList) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        getRecycleRdecord(); //重新调用获取回收站列表数据
        getRdecord({}); //重新调用获取站点列表数据
        siteRecycleBaseTables.value.selectedRowKeys = [] // 清空复选框
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
//删除已选所有回收站数据
const deleteSelectedAll = async () => {
  let keys: (string | number)[] = rowSelection.value;
  await deleteRecycleRecords({ ids: keys });
  siteRecycleBaseTables.value.selectedRowKeys = [] // 清空复选框
};
//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  let datas: DataList = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  getRecycleRdecord(datas);
};
const recycleTable = async () => {
  modAlProps.width = "L";
  modAlProps.title = "站点回收站";
  buttons.value = [];
  isVisible.value = true;
  isCancleBtn.value = false;
  isVisibleForm.value = false;
  getRecycleRdecord();
};
const switchChange = (record: DataList, type: any) => {
  let dataList: DataList[] = JSON.parse(JSON.stringify(configData.records));
  configData.records = JSON.parse(JSON.stringify(loop(dataList, record)));

  let param = {
    id: record.id,
    status: !type ? 1 : 0,
  };
  request
    .fetchSiteManageTabledDataIsOpen(param)
    .then((res: DataList) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        getRdecord(); // 手动处理，可以不再重新调取列表
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
const addChildSite = (record: DataList) => {
  if (!record.newChildPerm) return;
  parentTitle.value = record.siteName;
  parentId.value = record.id;
  modAlProps.width = "M";
  modAlProps.title = "新建站点";
  isVisible.value = true;
  isCancleBtn.value = true;
  isVisibleForm.value = true;
};
const buttonMessage = async (msg: DataList) => {
  //保存
  let form = SITEFORM.value.createSiteFrom;
  let formParams = SITEFORM.value.formParams;
  formParams.status = formParams.status ? 1 : 0;
  form
    .validate()
    .then(() => {
      let params: DataList = Object.assign({}, JSON.parse(JSON.stringify(formParams)));
      request
        .fetchSiteManageTabledDataAddSite(params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            getRdecord();
            message.success(res.message);
            isVisible.value = msg.text == "保存" ? false : true;
            let clearData = [
              "channelCopyOptions",
              "description",
              "seoDescription",
              "seoKeyword",
              "seoTitle",
              "siteDomain",
              "siteDomainAlias",
              "sitePath",
              "siteName",
            ];
            for (let item of clearData) {
              if (!(SITEFORM.value.formState[item] instanceof Array)) {
                SITEFORM.value.formState[item].value = "";
              } else {
                SITEFORM.value.formState[item] = [];
              }
            }
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });

      SITEFORM.value.resetFields();
    })
    .catch(() => {});
  //form.scrollToField();
};
const editSite = async (record: DataList) => {
  if (!record.editPerm) return;
  router.push({
    path: "/config/siteManage/detail",
    name: "站点详情",
    query: {
      id: record.id,
    },
  });
};

// 浏览
const scanSite = (record: DataList) => {
  if (record.scanUrl) {
    window.open(record.scanUrl);
  }
  console.log(record.scanUrl);
};
const confirmDelete = async (record: DataList) => {
  // 更改站点开启或关闭状态
  if (record.children instanceof Array) {
    return;
  }
  let params = {
    id: record.id,
  };
  await request
    .fetchSiteManageTabledDataMToRecycle(params)
    .then((res: DataList) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        getRdecord();
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
const deleteRecords = async (record: DataList) => {
  // 调接口删除数据
  if (record.children instanceof Array) {
    deleteTips.value =
      "请将该站点下的子站点编辑按钮重新绑定父级关系或移入回收站，再删除该站点";
  } else {
    deleteTips.value = "删除后的站点可以去站点回收站还原";
  }
};
//删除回收站中的数据
const deleteRecycleRecords = async (keys: {}) => {
  await request
    .fetchsiteManageTabledDataDelete(keys)
    .then((res: DataList) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        getRecycleRdecord();
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
const onSearchSite = () => {
  // 过滤条件筛选站点数据
  getRdecord();
};
const dragEnd = async (param: DataList) => {
  // 拖拽变换表格数据
  await request
    .fetchSiteManageTabledDataDrag(param)
    .then((res: DataList) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        getRdecord();
      } else {
        message.error(res.message);
        getRdecord();
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
const loop = (datalist: DataList[] = [], record: DataList): DataList[] => {
  // 递归遍历处理数据
  if (record.id) {
    for (let i in datalist) {
      if (datalist[i].id == record.id) {
        datalist[i].status = record.status ? true : false;
      } else if (datalist[i].children && datalist[i].children instanceof Array) {
        loop(datalist[i].children, record);
      }
    }
  } else {
    for (let i in datalist) {
      // 站点的isOpen字段为1是开启状态，0是手都冻关闭状态， 2是定时任务关闭状态, a-switch智能识别TS boolean类型
      datalist[i].status != 1
        ? (datalist[i].status = false)
        : (datalist[i].status = true);
      if (datalist[i].children && datalist[i].children instanceof Array) {
        loop(datalist[i].children, record);
      }
    }
  }
  return datalist;
};
// loop(dataList)
// configData.records = JSON.parse(JSON.stringify(dataList))
//onMounted
onMounted(() => {
  btnPerm.value = routerPerm();
  getRdecord();
});
</script>
<style lang="less" scoped>
//站点下的table样式微调
.siteTable {
  width: 100%;
  background-color: #fff;
  height: calc(100% - 72px);
  padding: 16px;

  .siteTable_header {
    display: flex;
    justify-content: space-between;
    padding-bottom: 16px;
    align-items: center;

    .siteStatus_label {
      font-size: 14px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      line-height: 14px;
      margin-right: 2px;
    }

    .ant-select-selector {
      width: 96px;
    }

    .icon-search {
      font-size: 20px;
      color: rgba(0, 0, 0, 0.45);
      position: absolute;
      right: 12px;
      top: 0px;
    }
  }

  .siteTable_header_right {
    width: 376px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .operation {
    margin-right: 16px;
  }

  .operation:nth-last-child(1) {
    margin-right: 0px;
  }
}

::v-deep(.ant-table-wrapper table > tbody > tr > td:nth-child(1)) {
  padding: 8px;
}

::v-deep(.ant-table-wrapper table > thead > tr > th:nth-child(1)) {
  padding-left: 8px;
}

::v-deep(.ant-table-cell:nth-last-of-type(1)) {
  text-align: right;
}

:v-deep(.ant-table-wrapper) {
  overflow: hidden;
}
</style>
<style>
.baseTable {
  position: relative;
}

.baseTable .aTable {
  height: fit-content;
  overflow: auto;
}

.baseTable .pagination {
}
</style>
<style>
.site_modal .ant-modal-body {
  margin-bottom: -6px;
}

.site_modal .tableFootContaienr {
  padding: 24px 0 10px 8px;
  width: 100%;
}

.siteTable .ant-table-fixed-columns-in-body {
  display: inline-block;
  width: 384px;
}
</style>
